package bjut.zrpc.core.optimization.scanner;


import bjut.zrpc.core.optimization.annotation.ZRpcScan;
import bjut.zrpc.core.optimization.annotation.ZRpcService;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/23 18:49
 */
public class ZRpcRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private ResourceLoader resourceLoader;
    private static final String BASE_PACKAGE = "basePackage";
    private static final String ZRPC_BASE_PACKAGE = "bjut.zrpc.core.optimization";

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {

        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(ZRpcScan.class.getName()));

        String[] basePackage;
        if (annotationAttributes != null) {
            basePackage = annotationAttributes.getStringArray(BASE_PACKAGE);
        } else {
            basePackage = new String[]{ClassUtils.getPackageName(annotationMetadata.getClass())};
            //basePackage = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName()};
        }


        ZRpcScanner zRpcScanner = new ZRpcScanner(registry, ZRpcService.class);
        ZRpcScanner componentScanner = new ZRpcScanner(registry, Component.class);

        if (resourceLoader != null) {
            zRpcScanner.setResourceLoader(resourceLoader);
            componentScanner.setResourceLoader(resourceLoader);
        }

        int scan = zRpcScanner.scan(basePackage);
        componentScanner.scan(ZRPC_BASE_PACKAGE);


    }
}
